<script setup>
import { ref, reactive } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import axios from 'axios';

import { inject } from 'vue';//引入
const router = inject('router');

const wwwHost = import.meta.env.VITE_APP_DOMAIN_URL

const form = ref(null)
const formData = reactive({
    username: '',
    password: '',
    email: '',
    mobile: '',
    rePassword: '',
});




const passwordValidator = (val) => {
    if (val.length > 0 && val.length <= 3) {
        return { result: false, message: '太简单了！再开动一下你的小脑筋吧！', type: 'error' };
    }
    if (val.length > 2 && val.length <= 6) {
        return { result: false, message: '还差一点点，就是一个完美的密码了！', type: 'warning' };
    }
    return { result: true, message: '太强了，你确定自己记得住吗！', type: 'success' };
};



const rePassword = (val) => {
    console.log("repassword:" + val)
    return new Promise((resolve) => {
        const timer = setTimeout(() => {
            resolve(formData.password === val);
            clearTimeout(timer);
        });
    })
};

const checkUsername = (val) => {
    console.log("invoke checkusername（）")
    const url = wwwHost + "/user/checkusername"
    return new Promise((resolve, reject) => {
        axios.post(url, formData).then(res => {
            if (!res.data.haseUsername) {
                 resolve(true)
            } else{
                resolve(false)
            }
        }).catch(err => {
            //给出错误提示                
            //alert(err)
            reject(err);
        })
    })
};

const onRegister = (validateResult, firstError, e) => {
    console.log('用户登录', formData)
    const url = wwwHost + "/user/register"
    if (validateResult.validateResult === true) {
        axios.post(url, formData).then(res => {
            console.log(res);

            if (res.data.isLogin) {
                MessagePlugin.success(res.data.msg);
                router.push("/")
            } else {
                MessagePlugin.warning(res.data.msg);
            }

        }).catch(err => {
            //给出错误提示                
            //alert(err)
            console.log(err);
        })
    } else {
        console.log('Validate Errors: ', validateResult);
        MessagePlugin.warning(validateResult.firstError);
    }
}


const FORM_RULES = {
    username: [
        { required: true, message: '用户名必填', type: 'error' },
        {
            min: 3,
            message: '至少需要两3个字符',
            type: 'error',
            trigger: 'blur',
        },
        {
            max: 32,
            message: '最长不能超过32个字符',
            type: 'error',
            trigger: 'blur',
        },
        { validator: checkUsername ,message:'该用户名不可用'}

    ],

    password: [
        { required: true, message: '密码必填', type: 'error' },
        { validator: passwordValidator }
    ],

    rePassword: [
        { required: true, message: '密码必填', type: 'error' },
        { validator: rePassword, message: '两次密码不一致' }

    ]

};
</script>

<template>
    <div class="max-w-md mx-auto mt-10 p-6 bg-white rounded-md shadow-md">
        <h1 class="text-2xl font-bold mb-4">用户注册</h1>
        <t-form :form="form" :rules="FORM_RULES" :data="formData" @reset="onReset" @submit="onRegister">
            <t-form-item label="用户名" name="username">
                <t-input type="text" v-model="formData.username">
                    <template #prefix-icon>
                        <t-icon name="user" />
                    </template>
                </t-input>
            </t-form-item>

            <t-form-item label="密码" name="password">
                <t-input type="password" v-model="formData.password">
                    <template #prefix-icon>
                        <t-icon name="lock-on" />
                    </template>
                </t-input>
            </t-form-item>

            <t-form-item label="重复密码" name="rePassword">
                <t-input type="password" v-model="formData.rePassword">
                    <template #prefix-icon>
                        <t-icon name="lock-on" />
                    </template>
                </t-input>
            </t-form-item>

            <t-form-item>
                <t-space size="small">
                    <t-button theme="primary" type="submit">注册</t-button>
                    <t-button theme="default" variant="base" type="reset">重置</t-button>
                </t-space>
            </t-form-item>
        </t-form>

    </div>
</template>